<template>
    <async-modal initHeight="400px" initWidth="600px" title="添加会签人" @update:visible="cancel">
        <template #modalBody>
            <el-form :model="formInfo" ref="ruleFormRef" label-width="100px">
                <el-form-item label="选择用户：" prop="userIds" :rules="[{required:true,message:'请选择用户',trigger:'change'}]">
                    <multipleRemoteSelect :property="'forUserId'" placeholder="" style="width: 100%;" @save="saveMult"></multipleRemoteSelect>
                </el-form-item>                               
            </el-form>
        </template>
        <template #modalFoot>
            <div class="event-button">
                <el-button type="primary" @click="onSubmit(ruleFormRef)">确定</el-button>
                <el-button @click="cancel">取消</el-button>            
            </div>
        </template> 
    </async-modal>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import AsyncModal from '@/components/Modal/index.vue';
import flowApi from '@/api/flow/index.ts';
import multipleRemoteSelect from '@/components/remoteSelect/multiple.vue';

let $emit = defineEmits(['closeDig','reQuery']);

const props = defineProps<{
    procInstanceId: String; 
}>();

interface FormInfo {
    userIds: any[];
    userList: any[];
}
const initialFormInfo:FormInfo = {
    userIds: [],
    userList: [], 
};

const formInfo = reactive({ ...initialFormInfo }); 
const cancel = ()=>{
    $emit('closeDig');
}
const saveMult = (msg: any) => {
    console.log('选择用户：',msg)
    formInfo.userIds = msg.ids;
    formInfo.userList = msg.items;
};
const ruleFormRef = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    try {
        await formEl.validate((valid, fields) => {
            if (valid) {
                submitForm();
            } else {
                console.log('error submit!', fields);
            }
        });
    } catch (error) {
        console.error('Error during form validation or submission:', error);
    }
}
const submitForm = async () => {
    try {
        showLoading();
        await flowApi.addCountersign({
            "procInstanceId": props.procInstanceId,
            "userList": formInfo.userList
        });
        ElMessage.success(`添加会签人成功！`);
        $emit('reQuery');
        $emit('closeDig');
    } catch (error) {
        console.error('Error during form submission:', error);
    } finally {
        hideLoading()
    }
}
</script>

<style scoped lang="scss">
</style>
